package com.sgb.kjwl.view.ui.fragment.manage;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.goods.utils.Constants;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentOrderListBinding;
import com.sgb.kjwl.di.self.DaggerSelfFragComponent;
import com.sgb.kjwl.di.self.SelfFragModule;
import com.sgb.kjwl.model.entity.user.OrderListEntity;
import com.sgb.kjwl.view.ui.activity.manage.WebsiteInfoActivity;
import com.sgb.kjwl.view.ui.activity.self.order.BaseLazyFragment;
import com.sgb.kjwl.view.ui.adapter.self.order.OrderListAdapter;
import com.sgb.kjwl.viewmodel.manage.AgentTotalOrderModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.util.LogUtil;
import com.swgk.core.util.MToast;

import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

/**
 *
 * 个人中心---商品--销售订单
 * 订单列表：8种
 * 采购订单：0待接单，10待确认，1待发货，2待收货，3已完成
 * 销售订单：4待接单，14待确认，5待发货，6待收货，7已完成
 * <p>
 * "type":"",//1采购订单 2销售订单
 * "orderState":""//订单状态（待接单 0  待签收 10 待支付 101 待发货102 已发货103  已完成7 已取消 8 ）
 */
public class AgentGoodsOrderStateFragment extends BaseLazyFragment {
    public static final String TAG = "";
    public static final String KEY_TYPE = "type";
    public static final String KEY_STATE = "STATE";
    public static final String ORDER_PROCESS_STATE = "ORDERPROCESSSTATE";

    private FragmentOrderListBinding binding;
    private String type = "";
    private String state = "";
    private String processState = "";
    private OrderListAdapter orderListAdapter;
    @Inject
    AgentTotalOrderModel viewModel;
    private boolean isLoadMore;
//    private OrderPersonWindow recordWindow;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onAttach(@NotNull Context context) {
        super.onAttach(context);
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerSelfFragComponent.builder()
                .appComponent(appComponent)
                .selfFragModule(new SelfFragModule())
                .build()
                .inject(this);
    }

    public static AgentGoodsOrderStateFragment newInstance(String type, String state, String processState) {
        AgentGoodsOrderStateFragment fragment = new AgentGoodsOrderStateFragment();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_TYPE, type);
        bundle.putString(KEY_STATE, state);
        bundle.putString(ORDER_PROCESS_STATE, processState);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NotNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_order_list, container, false);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        type = getArguments().getString(KEY_TYPE);
        state = getArguments().getString(KEY_STATE);
        processState = getArguments().getString(ORDER_PROCESS_STATE);
        initView();
//        initData();
    }

    private void initView() {
        if (orderListAdapter == null) {
            orderListAdapter = new OrderListAdapter(type);
        }
        orderListAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            int itemViewId = view.getId();
            switch (itemViewId) {
                case R.id.tv_title:
                    WebsiteInfoActivity.start(getActivity(), Objects.requireNonNull(orderListAdapter.getItem(position)).getJumpComNo(), WebsiteInfoActivity.WEBSITE_FOR_COMPANY, 0, 0);
                    break;
//                case R.id.img_cancel_order:
//                    MToast.showToast(getActivity(), "要取消订单吗");
//                    break;
                case R.id.tv_order_record:
                    // 跳转发票信息
                    ARouter.getInstance().build(Constants.ARouter.AR_INVOICE_DETAIL)
                            .withString("id", orderListAdapter.getItem(position).getId().toString())
                            .navigation();
                    break;
                default:
                    break;
            }
        });
        orderListAdapter.setOnItemClickListener((adapter, view, position) -> {
            MToast.showToast(getActivity(), "功能升级中，请前往PC端查看详情");
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.rlvView.setLayoutManager(layoutManager);
        binding.rlvView.addItemDecoration(new RecyclerCustomDecoration(0, 0, 0,
                getActivity().getResources().getDimension(R.dimen.dp10), getActivity().getResources().getColor(R.color.color_main_bg)));
        orderListAdapter.bindToRecyclerView(binding.rlvView);
//        orderListAdapter.setEmptyView(NoDataUtils.getInstance().getEmptyView(getActivity()));

        binding.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                viewModel.getOrderListModel(getContext(), type, state.split(","), processState, true);
                isLoadMore = true;
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                binding.refreshLayout.resetNoMoreData();
                viewModel.getOrderListModel(getContext(), type, state.split(","), processState, false);
                isLoadMore = false;
            }
        });
        viewModel.getShowBlankView().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if (s != null){
                    if (!TextUtils.isEmpty(s)){
                        MToast.showToast(getContext(), s);
                    }
                    showBlankView();
                }
            }
        });
        viewModel.getGoodOrderList().observe(getViewLifecycleOwner(), new Observer<List<OrderListEntity>>() {
            @Override
            public void onChanged(List<OrderListEntity> orderListEntities) {
                if (orderListEntities != null){
                    showStateView(orderListEntities);
                }
            }
        });
    }

    @Override
    public void initData() {
        LogUtil.e("initData===" + state);
        viewModel.getOrderListModel(getContext(), type, state.split(","), processState, false);
    }

    public void showStateView(List<OrderListEntity> data) {
        if (data.size() < 10) {
            binding.refreshLayout.setNoMoreData(true);
        }
        if (isLoadMore) {
            binding.refreshLayout.finishLoadMore(true);
            if (data.size() == 0) {
                binding.refreshLayout.setEnableLoadMore(false);
            } else {
                orderListAdapter.addData(data);
            }
        } else {
            //如果是第一页 那么设置最新数据替换
            binding.refreshLayout.finishRefresh(true);
            if (data.size() == 0) {
                binding.rootBlankView.blankView.setVisibility(View.VISIBLE);
            } else {
                orderListAdapter.setNewData(data);
            }
        }
    }


    public void showBlankView() {
        if (isLoadMore) {
            binding.refreshLayout.finishLoadMore(false);
        } else {
            binding.refreshLayout.finishRefresh(false);
            binding.rootBlankView.blankView.setVisibility(View.VISIBLE);
        }
    }


//    public void showRecordPop(List<OrderPersonEntity> data) {
//        recordWindow.setData(data);
//        recordWindow.showDownPopwindow(binding.grayLayout, true);
//    }
}
